print('enter post_script.py')
import sys

print(sys.executable)
import hashlib
import os
import json
import git

Import("env", "projenv")
print(env['PLATFORM'])
def BuildSharedLibrary(env, variant_dir, src_dir, src_filter=None):
    """
    Args:
        env:
        variant_dir:
        src_dir:
        src_filter:
    """
    env.ProcessUnFlags(env.get("BUILD_UNFLAGS"))
    return env.SharedLibrary(env.subst(variant_dir), src_dir)
for e in [env, projenv]:
    if env['PIOPLATFORM'] in ['sylixos_arm', 'sylixos_x86']:
        e.Replace(LINKFLAGS=[i for i in e['LINKFLAGS'] if i not in ['-nostartfiles', '-nostdlib']])
        e.Append(
            _LIBFLAGS=" -LF:/workspace/base_arm/libsylixos/Debug -LF:/workspace/base_arm/libcextern/Debug -lvpmpdm -lcextern -ldsohandle -lstdc++ -lgcc -lm")
        e.Append(LINKFLAGS=['-fPIC', '-nostartfiles', '-nostdlib', "--specs=nosys.specs"])
    elif env['PIOPLATFORM'] in ['windows_x86']:
        e.Append(
            _LIBFLAGS=" -Llib/SOEM/oshw/win32/wpcap/Lib -lwinmm -lws2_32 -liphlpapi -lpthread -lstdc++ -lgcc -lm")
    else:
        e.Replace(LINKFLAGS=[i for i in e['LINKFLAGS'] if i not in ['-nostartfiles', '-nostdlib']])
        e.Append(LINKFLAGS=['-nostartfiles', '-nostdlib', "--specs=nosys.specs"])
# access to global construction environment
# print env

# access to project construction environment
# print projenv

# Dump construction environments (for debug purpose)
# print( env.Dump())
# print (projenv.Dump())
js = {'lib': {}}
if os.path.exists("build.json"):
    with open("build.json") as fp:
        js = json.load(fp)

for lib in projenv['__PIO_LIB_BUILDERS']:
    repo = git.Repo(lib.path, search_parent_directories=True)
    sha = repo.head.object.hexsha
    # print(lib.name, lib.path, sha)
    js['lib'].update({lib.name: {"ID": sha}})

js['CPPDEFINES'] = env['CPPDEFINES'] + projenv['CPPDEFINES']
# def before_buildprog(source, target, env):
#     print("before_buildprog")
#     print(os.getcwd())
# if os.path.exists('web'):
#     os.system("makefsdata.exe web")

# env.Append(ldscript='stm32f103ve.ld')

BUILD_NUMBER = os.environ.get('CI_BUILD_NUMBER') or os.environ.get('BUILD_NUMBER') or "0"
print("BUILD_NUMBER=%s\n" % BUILD_NUMBER)
projenv.Append(CPPDEFINES=['BUILD_NUMBER=%s' % BUILD_NUMBER])
env.Append(CPPDEFINES=['BUILD_NUMBER=%s' % BUILD_NUMBER])
js['build'] = BUILD_NUMBER


def before_upload(source, target, env):
    print("before_upload")
    # do some actions


def after_upload(source, target, env):
    print("after_upload")
    # do some actions


def buildMD5(source, target, env):
    print("buildMD5")
    f = str(target[0])
    print(f, type(f))
    fh = open(f, "rb")
    fr = fh.read()
    md5key = hashlib.md5(fr).hexdigest()

    # Store new PLC filename based on md5 key
    f = open("lastbuildPLC.md5", "w")
    f.write(md5key)
    f.close()


env.AddPreAction("upload", before_upload)
env.AddPostAction("upload", after_upload)
# env.AddPreAction("buildprog", before_buildprog)
env.AddPostAction("$BUILD_DIR/firmware.bin", buildMD5)
with open("build.json", "w+", encoding='utf-8') as fp:
    json.dump(js, fp, indent=2)
